package com.zhsj.OkeHomeConsumption.ui.activity.wallet;

import android.graphics.Color;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zhsj.OkeHomeConsumption.R;
import com.zhsj.OkeHomeConsumption.common.Constants;
import com.zhsj.OkeHomeConsumption.common.OkeHomeConsumptionApi;
import com.zhsj.OkeHomeConsumption.empty.FormalUserInfo;
import com.zhsj.OkeHomeConsumption.network.HttpClient;
import com.zhsj.OkeHomeConsumption.network.JsonResponseHandler;
import com.zhsj.OkeHomeConsumption.other.TimeChecker;
import com.zhsj.OkeHomeConsumption.other.URLEntity;
import com.zhsj.OkeHomeConsumption.utils.JsonUtils;
import com.zhsj.OkeHomeConsumption.utils.LogUtils;
import com.zhsj.OkeHomeConsumption.utils.ParamMatchUtils;
import com.zhsj.OkeHomeConsumption.utils.SignUtil;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * Created by zwj on 2017/10/15.
 * 开通钱包--验证手机号
 */

public class OpenWalletFragment extends BaseFragment implements View.OnClickListener{

    /**
     * 计时器
     */
    private TimeChecker timeChecker = null;
    /**
     * 实例化ProgressDrawableAlertDialog
     */
    private ProgressDrawableAlertDialog pDialogUtils = null;

    //左标提
    private TextView topbar_textview_leftitle;
    //标题
    private TextView topbar_textview_title;

    //手机号
    private ClearEditText mPhone;
    //验证码
    private ClearEditText mCode;
    //发送验证码
    private TextView mSend;
    private SendSmsCodeCount mSendSmsCodeCount;
    //下一步
    private TextView next;

    private FormalUserInfo userInfo;
    //获取验证码返回的token
    private String tokenCode;
    //验证手机号返回的token
    private String mToken;

    //0是个人  1是企业
    private String flag_send = "0";

    //当前时间戳
    private String nowTime;

    //1开通钱包  2修改信息
    private int tag = 1;
    //用户所属商户号
    private String oid_partner;
    //钱包状态
    private String stat_user;
    //证件号码
    private String no_idcard;
    //姓名
    private String name_user;
    //支付密码
    private LinearLayout password_linear;
    private ClearEditText password_edit;
    private View password_view;

    //是否是企业钱包--有值是企业  空是个人
    private String type_register;

    public static OpenWalletFragment newInstance(String type_register, FormalUserInfo userInfo, String oid_partner, String stat_user, String name_user, String no_idcard, int tag) {
        
        Bundle args = new Bundle();
        OpenWalletFragment fragment = new OpenWalletFragment();
        args.putSerializable("userInfo",userInfo);
        args.putString("type_register", type_register);
        args.putString("oid_partner", oid_partner);
        args.putString("stat_user", stat_user);
        args.putString("name_user", name_user);
        args.putString("no_idcard", no_idcard);
        args.putInt("tag", tag);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userInfo = (FormalUserInfo) getArguments().getSerializable("userInfo");
        type_register = getArguments().getString("type_register");
        oid_partner = getArguments().getString("oid_partner");
        stat_user = getArguments().getString("stat_user");
        name_user = getArguments().getString("name_user");
        no_idcard = getArguments().getString("no_idcard");
        tag = getArguments().getInt("tag");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_open_wallet, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initListener();
        judgmentIdentity();
    }

    /**
     * 判断身份
     */
    private void judgmentIdentity(){
                //个人身份
                flag_send = "0";
    }


    private void initView(View view){
        topbar_textview_leftitle = (TextView) view.findViewById(R.id.topbar_textview_leftitle);
        topbar_textview_leftitle.setVisibility(View.VISIBLE);
        topbar_textview_title = (TextView) view.findViewById(R.id.topbar_textview_title);
        topbar_textview_title.setText("开通钱包");
        mPhone =  view.findViewById(R.id.phone);
        mCode = (ClearEditText) view.findViewById(R.id.code);
        mSend = (TextView) view.findViewById(R.id.send);
        next = (TextView) view.findViewById(R.id.next);
        password_linear = (LinearLayout) view.findViewById(R.id.password_linear);
        password_edit = (ClearEditText) view.findViewById(R.id.password_edit);
        password_view = view.findViewById(R.id.password_view);
        if (tag == 2){
            if ("1".equals(flag_send)){
                //企业修改信息
                password_linear.setVisibility(View.VISIBLE);
                password_edit.setVisibility(View.VISIBLE);
                password_view.setVisibility(View.VISIBLE);
            }
        }else {
            password_linear.setVisibility(View.GONE);
            password_edit.setVisibility(View.GONE);
            password_view.setVisibility(View.GONE);
        }
    }

    private void initListener(){
        topbar_textview_leftitle.setOnClickListener(this);
        mSend.setOnClickListener(this);
        next.setOnClickListener(this);
        mSendSmsCodeCount = new SendSmsCodeCount(60 * 1000, 100);
        timeChecker = new TimeChecker(TimeOutHandler.timeOutHandler, Constants.TIME_OUT);
        pDialogUtils = new ProgressDrawableAlertDialog(_mActivity);


    }

    //钱包获取手机验证码
    public void sendCode(String sign_type, String user_id, String mob_bind, String flag_send) {
        mSendSmsCodeCount.start();
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        mSendCodeHashMap.put("sign_type", sign_type);
        mSendCodeHashMap.put("user_id", user_id);
        mSendCodeHashMap.put("mob_bind", mob_bind);
        mSendCodeHashMap.put("flag_send", flag_send);

        LogUtils.e("mSendCodeHashMap", mSendCodeHashMap.toString());
        //post 传参
        paramMaps.put("sign_type", sign_type);
        paramMaps.put("user_id", user_id);
        paramMaps.put("mob_bind", mob_bind);
        paramMaps.put("flag_send", flag_send);

        // 网络计时器及线程
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.post(OkeHomeConsumptionApi.WALLET_PHONE_CODE, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                try {
                    LogUtils.e("content_钱包获取手机验证码", "content=" + content);
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        JSONObject data = jsonObject.optJSONObject("data");
                        tokenCode = data.optString("token");
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    //钱包获取手机验证码--修改
    public void modifysendCode(String oid_partner, String sign_type, String user_id, String mob_bind, String flag_send) {
        mSendSmsCodeCount.start();
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        mSendCodeHashMap.put("sign_type", sign_type);
        mSendCodeHashMap.put("user_id", user_id);
        mSendCodeHashMap.put("mob_bind", mob_bind);
        mSendCodeHashMap.put("flag_send", flag_send);
        mSendCodeHashMap.put("oid_partner", oid_partner);

        LogUtils.e("mSendCodeHashMap", mSendCodeHashMap.toString());
        //post 传参
        paramMaps.put("sign_type", sign_type);
        paramMaps.put("user_id", user_id);
        paramMaps.put("mob_bind", mob_bind);
        paramMaps.put("flag_send", flag_send);
        paramMaps.put("oid_partner", oid_partner);

        // 网络计时器及线程
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.post(OkeHomeConsumptionApi.WALLET_PHONE_CODE, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                try {
                    LogUtils.e("content_钱包获取手机验证码", "content=" + content);
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        JSONObject data = jsonObject.optJSONObject("data");
                        tokenCode = data.optString("token");
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    //钱包获取手机验证码--修改--企业

    public void modifysendEnterCode(String oid_partner, String sign_type, String user_id, String pwd_pay, String flag_check, String risk_item, String mob_bind) {
        mSendSmsCodeCount.start();
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        mSendCodeHashMap.put("sign_type", sign_type);
        mSendCodeHashMap.put("user_id", user_id);
        mSendCodeHashMap.put("pwd_pay", pwd_pay);
        mSendCodeHashMap.put("flag_check", flag_check);
        mSendCodeHashMap.put("oid_partner", oid_partner);
        mSendCodeHashMap.put("risk_item", risk_item);
        mSendCodeHashMap.put("mob_bind", mob_bind);

        LogUtils.e("mSendCodeHashMap", mSendCodeHashMap.toString());
        //post 传参
        paramMaps.put("sign_type", sign_type);
        paramMaps.put("user_id", user_id);
        paramMaps.put("pwd_pay", pwd_pay);
        paramMaps.put("flag_check", flag_check);
        paramMaps.put("oid_partner", oid_partner);
        paramMaps.put("risk_item", risk_item);
        paramMaps.put("mob_bind", mob_bind);

        // 网络计时器及线程
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.post(OkeHomeConsumptionApi.MODIFY_WALLET_PHONE_CODE, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                try {
                    LogUtils.e("content_钱包获取手机验证码", "content=" + content);
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        JSONObject data = jsonObject.optJSONObject("data");
                        tokenCode = data.optString("token");
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    //验证验证码是否正确
    public void phoneCodeIsOK(String sign_type, String user_id, String token, String verify_code) {
        // post传参使用的HashMap
        HashMap<String, String> paramMaps = new HashMap<String, String>();
        // 生成sign值所使用的HashMap
        HashMap<String, String> mSendCodeHashMap = new HashMap<String, String>();
//        mSendCodeHashMap.put("token", Constants.TOKEN);
        mSendCodeHashMap.put("v", Constants.APPVERSION);
        mSendCodeHashMap.put("t", Constants.TIME);
        mSendCodeHashMap.put("deviceId", URLEntity.getInstance().getImei());
        mSendCodeHashMap.put("platform", Constants.PLAFORM);
        mSendCodeHashMap.put("deviceToken", Constants.DEVICETOKEN);
        mSendCodeHashMap.put("client", Constants.CLIENT);
        mSendCodeHashMap.put("sign_type", sign_type);
        mSendCodeHashMap.put("user_id", user_id);
        mSendCodeHashMap.put("token", token);
        mSendCodeHashMap.put("verify_code", verify_code);

        LogUtils.e("mSendCodeHashMap", mSendCodeHashMap.toString());
        //post 传参
        paramMaps.put("sign_type", sign_type);
        paramMaps.put("user_id", user_id);
        paramMaps.put("token", token);
        paramMaps.put("verify_code", verify_code);

        // 网络计时器及线程
        TimeOutHandler.pDialogUtils = pDialogUtils;
        pDialogUtils.show();
        timeChecker.start();
        // 获取sign签名
        Constants.SIGN = SignUtil.getInstance().getSign(mSendCodeHashMap);
        LogUtils.e("mSendCodeHashMap", SignUtil.getInstance().getSign(mSendCodeHashMap));
        HttpClient.post(OkeHomeConsumptionApi.WALLET_PHONE_CODE_ISOK, paramMaps, new JsonResponseHandler() {

            @Override
            public void onSuccess(int statusCode, String content) {
                // TODO Auto-generated method stub
                super.onSuccess(statusCode, content);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                try {
                    LogUtils.e("content_验证手机验证码", "content=" + content);
                    JSONTokener jsonT = new JSONTokener(content);
                    JSONObject jsonOBJ = (JSONObject) jsonT.nextValue();
                    String code = jsonOBJ.optString("code");
                    String message = jsonOBJ.optString("message");
                    if (code.equals("N000000")) {
                        // 数据对接正常
                        JSONObject jsonObject = jsonOBJ.optJSONObject("data");
                        JSONObject data = jsonObject.optJSONObject("data");
                        String ret_code = data.optString("ret_code");
                        String ret_msg = data.optString("ret_msg");
                        mToken = data.optString("token");
                        if ("0000".equals(ret_code)) {
                            startForResult(OpenWalletMessageFragment.newInstance(type_register, userInfo, mToken, mPhone.getText().toString().trim(), oid_partner, stat_user, name_user, no_idcard, tag), 1);
                        }else {
                            showShortToast(ret_msg + "");
                        }
                    } else if (code.equals(Constants.STATUSTOKENERROR)) {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    } else {
                        if (!message.equals("null")) {
                            showShortToast(message);
                        }
                    }
                } catch (Exception ex) {
                    LogUtils.e("DresserPartnerRegisterPost", "失败 ");
                }
            }

            @Override
            public void onFailure(Throwable e) {
                // TODO Auto-generated method stub
                super.onFailure(e);
                timeChecker.check();
                pDialogUtils.dismiss();
                TimeOutHandler.pDialogUtils = null;
                LogUtils.e("onFailure", "" + e.toString());
            }
        });
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:
                if (resultCode == RESULT_OK){
                    setFragmentResult(RESULT_OK, new Bundle());
                    _mActivity.onBackPressed();
                }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.topbar_textview_leftitle:
                _mActivity.onBackPressed();
                break;
            case R.id.send:
                //发送验证码
                check(mPhone.getText().toString().trim());
                if (tag == 1) {
                    sendCode("RSA", userInfo.getId() + "", mPhone.getText().toString().trim(), flag_send);
                }else {
                        modifysendCode(oid_partner, "RSA", userInfo.getId() + "", mPhone.getText().toString().trim(), "3");
                }
                break;
            case R.id.next:
                //下一步
//                start(OpenWalletMessageFragment.newInstance(userInfo, mToken));
                phoneCodeIsOK("RSA",userInfo.getId() + "", tokenCode, mCode.getText().toString().trim());
                break;
        }
    }

    private List<HashMap<String, String>> hashMapLists;
    /**
     * 风控参数
     * @return
     */
    public String SubmitCaseContent() {
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String content = "";
        if (hashMapLists == null)
            hashMapLists = new ArrayList<>();
        if (hashMapLists.size() > 0)
            hashMapLists.clear();

        HashMap<String, String> map = new HashMap<>();
        map.put("user_info_dt_register",df.format(new Date()));

        hashMapLists.add(map);

        if (hashMapLists == null) {
            return "";
        }
        StringBuilder mStringBuilder = new StringBuilder();

        for (int i = 0; i < hashMapLists.size(); i++) {
            String hashMapToJson = JsonUtils.hashMapToJson(hashMapLists.get(i));
            mStringBuilder.append(hashMapToJson).append(",");
        }
        if (mStringBuilder.length() > 0) {
            String substring = mStringBuilder.toString().substring(0, mStringBuilder.toString().lastIndexOf(","));
            content = substring;
        } else {

        }
        return content;
    }


    /**
     * 检测手机号
     * @param phone
     * @return
     */
    private boolean check(String phone) {
        if (TextUtils.isEmpty(phone)) {
            showShortToast("请填写手机号");
            return false;
        }

        if (!ParamMatchUtils.isPhoneAvailable(phone)) {
            showShortToast("请填写正确的手机号");
            return false;
        }
        return true;
    }

    class SendSmsCodeCount extends CountDownTimer {

        public SendSmsCodeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            mSend.setEnabled(true);
            mSend.setTextColor(Color.parseColor("#79AB1C"));
            mSend.setGravity(Gravity.CENTER);
            mSend.setTextSize(14);
            mSend.setText("发送");
        }

        @Override
        public void onTick(long millisUntilFinished) {
            mSend.setEnabled(false);
            if (millisUntilFinished / 1000 == 0) {
                onFinish();
            } else {
                mSend.setText(millisUntilFinished / 1000 + "");
                mSend.setTextColor(Color.parseColor("#B2B2B2"));
                mSend.setGravity(Gravity.CENTER);
                mSend.setTextSize(14);
            }
        }
    }
}
